﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using System.Windows.Controls.DataVisualization.Charting;
using System.Threading;
using SL4PopupMenu;
using VAdvantage.Classes;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Utility;

namespace VAdvantage.Apps
{
    public partial class DashBoard : CFrame
    {

        /// <summary>
        /// Chart Types to be used in the application
        /// </summary>
        enum enmChartType
        {
            Column = 1,
            Line = 2,
            Pie = 3,
            Bar = 4
        }


        private int m_currentPage = 0;
        List<MChart> m_loaded = new List<MChart>();
        List<MChart> m_Currentloaded = new List<MChart>();
        //private VLogger log = new VLogger(typeof(this).FullName);
        private MChart m_CurrentChart;


        public DashBoard()
        {
            InitializeComponent();
            Envs.RegisterWindowForm(this);
            bPrev.IsEnabled = false;
            grid1.ShowGridLines = false;

            //BusyWindow.IsBusy = true;
            ThreadPool.QueueUserWorkItem(delegate
            {
                MChart chart = new MChart(Envs.GetCtx(), 0, null);
                MChart[] charts = MChart.GetCharts();

                for (int i = 0; i <= charts.Length - 1; i++)
                {
                    m_loaded.Add(charts[i]);
                }

                if (charts.Length > 4)
                    Dispatcher.BeginInvoke(() => bNext.IsEnabled = true);
                else
                    Dispatcher.BeginInvoke(() => bNext.IsEnabled = false);

                for (int i = 0; i <= charts.Length - 1; i++)
                {
                    if (i >= 4)
                    {
                        break;
                    }

                    int row = i / 2;
                    int col = i % 2;

                    //AddChart(charts[i], row, col);

                    try
                    {
                        bool loadchart = false;
                        Dispatcher.BeginInvoke(delegate
                        {
                            newChart = new Chart();
                            newChart.Tag = charts[i].Get_ID();
                            newChart.Title = charts[i].GetName();

                            var pm1 = new PopupMenu();
                            pm1.AddItem("Edit Series", EditSeries_Click);
                            pm1.AddItem("Zoom", ZoomChart_Click);
                            pm1.AddSeparator();

                            var chartType = new PopupMenu();
                            chartType.AddItem("Column", ColumnSeries_Click);
                            chartType.AddItem("Pie", PieSeries_Click);
                            chartType.AddItem("Line", LineSeries_Click);

                            pm1.AddSubMenu(chartType, "Chart Type", "Images/arrow.png", null, null, false, null);
                            pm1.AddTrigger(TriggerTypes.RightClick, newChart);

                            // Showing main menu
                            pm1.Showing += (sender, e) =>
                            {
                                selectedChart = (Chart)sender;
                            };

                            Grid.SetRow(newChart, row);
                            Grid.SetColumn(newChart, col);
                            this.grid1.Children.Add(newChart);

                            loadchart = true;
                        });

                        while (!loadchart)
                            Thread.Sleep(10);

                        AddSeriesToChart(newChart, charts[i]);

                    }
                    catch
                    {
                        //BusyWindow.IsBusy = false;
                    }
                }
            });


        }

        private void AddChart(MChart chart, int row, int col)
        {
            try
            {
                Chart newChart = new Chart();
                newChart.Tag = chart.Get_ID();
                newChart.Title = chart.GetName();
                newChart.FontSize = 10;

                Grid.SetRow(newChart, row);
                Grid.SetColumn(newChart, col);
                this.grid1.Children.Add(newChart);
            }
            catch
            {
                //BusyWindow.IsBusy = false;
            }
        }


        void UpdateChartType(enmChartType chartType)
        {
            if (chartType == enmChartType.Bar)
                newSeries = new BarSeries();
            else if (chartType == enmChartType.Line)
                newSeries = new LineSeries();
            else if (chartType == enmChartType.Column)
                newSeries = new ColumnSeries();
            else if (chartType == enmChartType.Pie)
                newSeries = new PieSeries();
        }

        private int univValue = 42;
        //ColumnSeries newSeries;
        //BarSeries newSeries;
        //LineSeries newSeries;
        DataPointSeries newSeries;


        /// <summary>
        /// Add Series to Chart
        /// </summary>
        /// <param name="newChart">new chart to be added</param>
        /// <param name="chart">Chart from the database</param>
        private void AddSeriesToChart(Chart newChart, MChart chart)
        {
            try
            {
                MSeries[] series = MSeries.Get(chart.Get_ID());

                string sql = "";
                for (int i = 0; i <= series.Length - 1; i++)
                {
                    univValue++;


                    bool loadseries = false;
                    Dispatcher.BeginInvoke(delegate
                    {
                        if (int.Parse(chart.GetChartType()) == (int)enmChartType.Bar)
                            newSeries = new BarSeries();
                        else if (int.Parse(chart.GetChartType()) == (int)enmChartType.Column)
                            newSeries = new ColumnSeries();
                        else if (int.Parse(chart.GetChartType()) == (int)enmChartType.Line)
                            newSeries = new LineSeries();
                        else if (int.Parse(chart.GetChartType()) == (int)enmChartType.Pie)
                            newSeries = new PieSeries();

                        newSeries.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                        newSeries.IndependentValuePath = "Key";
                        newSeries.DependentValuePath = "Value";
                        newSeries.Name = series[i].GetName();
                        newSeries.Tag = series[i].Get_ID();

                        loadseries = true;
                    });

                    while (!loadseries)
                        Thread.Sleep(10);

                    loadseries = false;

                    MPrintColor seriesColor = MPrintColor.Get(Envs.GetCtx(), series[i].GetAD_Series_Color_ID());

                    sql = series[i].GetSql(chart.IsShowZeroSeries(), "");
                    DataSet ds = DB.ExecuteDataset(sql, null);

                    if (ds.Tables[0].Rows.Count <= 25)
                    {
                        KeyValuePair<String, double>[] data = new KeyValuePair<string, double>[] { };
                        ICollection<KeyValuePair<string, double>> collection = new Dictionary<String, double>();
                        for (int v = 0; v <= ds.Tables[0].Rows.Count - 1; v++)
                        {

                            string colX = ds.Tables[0].Rows[v]["ColX"].ToString();
                            double colY = double.Parse(ds.Tables[0].Rows[v]["ColY"].ToString());
                            KeyValuePair<string, double> local = new KeyValuePair<string, double>(colX, colY);
                            collection.Add(local);
                        }

                        data = collection.ToArray();
                        bool isLogarithmic = series[i].IsLogarithmic();

                        Dispatcher.BeginInvoke(delegate
                        {
                            if (int.Parse(chart.GetChartType()) != (int)enmChartType.Pie)
                            {
                                LinearAxis la = new LinearAxis();
                                la.Orientation = AxisOrientation.Y;
                                if (!isLogarithmic)
                                    la.Minimum = 0;

                                newChart.Axes.Add(la);
                            }
                            newSeries.ItemsSource = data;
                            newChart.Series.Add(newSeries);
                            loadseries = true;
                            //BusyWindow.IsBusy = false;
                        });

                        while (!loadseries)
                            Thread.Sleep(10);
                        //this.LayoutRoot.Children.Add(newChart);
                    }



                }

            }
            catch (Exception ex)
            {
                //BusyWindow.IsBusy = false;
            }
        }


        Chart newChart;
        Chart selectedChart;

        void EditSeries_Click(object sender, EventArgs e)
        {
            AWindow win = new AWindow();
            ThreadPool.QueueUserWorkItem(delegate
            {
                int AD_Window_ID = win.GetWindowID("DashBoard");		// hardcoded
                if (AD_Window_ID <= 0)
                    return;

                Dispatcher.BeginInvoke(delegate
                {
                    //this.Close();
                    win.InitWindow(AD_Window_ID, Query.GetEqualQuery("D_Chart_ID", int.Parse(selectedChart.Tag.ToString())));
                    win.Show();
                });
            });
        }


        void ProcessChartChange(enmChartType chartType)
        {
            if (selectedChart.Axes.Count > 0)
            {
                //Remove any existing axes or series from the chart
                for (int ax = 0; ax <= selectedChart.Axes.Count - 1; ax++)
                    selectedChart.Axes.RemoveAt(ax);
            }


            if (selectedChart.Series.Count > 0)
            {
                int count = selectedChart.Series.Count - 1;
                for (int ax = 0; ax <= count; ax++)
                {
                    KeyValuePair<string, double>[] data = ((selectedChart.Series[0] as DataPointSeries).ItemsSource as KeyValuePair<string, double>[]);
                    int seriesID = int.Parse((selectedChart.Series[0] as DataPointSeries).Tag.ToString());
                    string name = (selectedChart.Series[0] as DataPointSeries).Name;
                    //MSeries mseries = new MSeries(Envs.GetCtx(), seriesID, null);

                    if (chartType == enmChartType.Line)
                        newSeries = new LineSeries();
                    else if (chartType == enmChartType.Pie)
                        newSeries = new PieSeries();
                    else if (chartType == enmChartType.Column)
                        newSeries = new ColumnSeries();

                    newSeries.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                    newSeries.IndependentValuePath = "Key";
                    newSeries.DependentValuePath = "Value";
                    newSeries.Name = name;
                    newSeries.Tag = seriesID;

                    if (chartType != enmChartType.Pie)
                    {
                        LinearAxis la = new LinearAxis();
                        la.Orientation = AxisOrientation.Y;
                        selectedChart.Axes.Add(la);
                    }

                    newSeries.ItemsSource = data;

                    selectedChart.Series.RemoveAt(ax);
                    selectedChart.Series.Add(newSeries);
                }
            }
        }

        void PieSeries_Click(object sender, EventArgs e)
        {
            ProcessChartChange(enmChartType.Pie);
        }



        void ColumnSeries_Click(object sender, EventArgs e)
        {
            ProcessChartChange(enmChartType.Column);
        }


        void LineSeries_Click(object sender, EventArgs e)
        {
            ProcessChartChange(enmChartType.Line);
        }

        bool isZoom = false;
        void ZoomChart_Click(object sender, EventArgs e)
        {
            PopupMenuItem menuitem = (PopupMenuItem)sender;

            if (!isZoom)
            {
                menuitem.Header = "Normal";
                isZoom = true;
                if ((Chart)grid1.Children[1] == selectedChart)
                {
                    if (grid1.Children.Count > 2)
                        grid1.Children[2].Visibility = System.Windows.Visibility.Collapsed;
                    if (grid1.Children.Count > 3)
                        grid1.Children[3].Visibility = System.Windows.Visibility.Collapsed;
                    if (grid1.Children.Count > 4)
                        grid1.Children[4].Visibility = System.Windows.Visibility.Collapsed;

                    grid1.ColumnDefinitions[0].Width = new GridLength(100, GridUnitType.Star);
                    grid1.RowDefinitions[0].Height = new GridLength(100, GridUnitType.Star);
                    grid1.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Star);
                    grid1.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Star);
                }
                else if ((Chart)grid1.Children[2] == selectedChart)
                {
                    if (grid1.Children.Count > 1)
                        grid1.Children[1].Visibility = System.Windows.Visibility.Collapsed;
                    if (grid1.Children.Count > 3)
                        grid1.Children[3].Visibility = System.Windows.Visibility.Collapsed;
                    if (grid1.Children.Count > 4)
                        grid1.Children[4].Visibility = System.Windows.Visibility.Collapsed;

                    grid1.ColumnDefinitions[0].Width = new GridLength(0, GridUnitType.Star);
                    grid1.RowDefinitions[0].Height = new GridLength(100, GridUnitType.Star);
                    grid1.ColumnDefinitions[1].Width = new GridLength(100, GridUnitType.Star);
                    grid1.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Star);
                }
                else if ((Chart)grid1.Children[3] == selectedChart)
                {
                    if (grid1.Children.Count > 1)
                        grid1.Children[1].Visibility = System.Windows.Visibility.Collapsed;
                    if (grid1.Children.Count > 2)
                        grid1.Children[2].Visibility = System.Windows.Visibility.Collapsed;
                    if (grid1.Children.Count > 4)
                        grid1.Children[4].Visibility = System.Windows.Visibility.Collapsed;

                    grid1.ColumnDefinitions[0].Width = new GridLength(100, GridUnitType.Star);
                    grid1.RowDefinitions[0].Height = new GridLength(0, GridUnitType.Star);
                    grid1.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Star);
                    grid1.RowDefinitions[1].Height = new GridLength(100, GridUnitType.Star);
                }
                else if ((Chart)grid1.Children[4] == selectedChart)
                {
                    if (grid1.Children.Count > 1)
                        grid1.Children[1].Visibility = System.Windows.Visibility.Collapsed;
                    if (grid1.Children.Count > 2)
                        grid1.Children[2].Visibility = System.Windows.Visibility.Collapsed;
                    if (grid1.Children.Count > 3)
                        grid1.Children[3].Visibility = System.Windows.Visibility.Collapsed;

                    grid1.ColumnDefinitions[0].Width = new GridLength(0, GridUnitType.Star);
                    grid1.RowDefinitions[0].Height = new GridLength(0, GridUnitType.Star);
                    grid1.ColumnDefinitions[1].Width = new GridLength(100, GridUnitType.Star);
                    grid1.RowDefinitions[1].Height = new GridLength(100, GridUnitType.Star);
                }
            }
            else
            {
                menuitem.Header = "Zoom";
                isZoom = false;
                if ((Chart)grid1.Children[1] == selectedChart)
                {
                    if (grid1.Children.Count > 2)
                        grid1.Children[2].Visibility = System.Windows.Visibility.Visible;
                    if (grid1.Children.Count > 3)
                        grid1.Children[3].Visibility = System.Windows.Visibility.Visible;
                    if (grid1.Children.Count > 4)
                        grid1.Children[4].Visibility = System.Windows.Visibility.Visible;

                }
                else if ((Chart)grid1.Children[2] == selectedChart)
                {
                    if (grid1.Children.Count > 1)
                        grid1.Children[1].Visibility = System.Windows.Visibility.Visible;
                    if (grid1.Children.Count > 3)
                        grid1.Children[3].Visibility = System.Windows.Visibility.Visible;
                    if (grid1.Children.Count > 4)
                        grid1.Children[4].Visibility = System.Windows.Visibility.Visible;
                }
                else if ((Chart)grid1.Children[3] == selectedChart)
                {
                    if (grid1.Children.Count > 1)
                        grid1.Children[1].Visibility = System.Windows.Visibility.Visible;
                    if (grid1.Children.Count > 2)
                        grid1.Children[2].Visibility = System.Windows.Visibility.Visible;
                    if (grid1.Children.Count > 4)
                        grid1.Children[4].Visibility = System.Windows.Visibility.Visible;
                }
                else if ((Chart)grid1.Children[4] == selectedChart)
                {
                    if (grid1.Children.Count > 1)
                        grid1.Children[1].Visibility = System.Windows.Visibility.Visible;
                    if (grid1.Children.Count > 2)
                        grid1.Children[2].Visibility = System.Windows.Visibility.Visible;
                    if (grid1.Children.Count > 3)
                        grid1.Children[3].Visibility = System.Windows.Visibility.Visible;
                }

                grid1.ColumnDefinitions[0].Width = new GridLength(50, GridUnitType.Star);
                grid1.RowDefinitions[0].Height = new GridLength(50, GridUnitType.Star);
                grid1.ColumnDefinitions[1].Width = new GridLength(50, GridUnitType.Star);
                grid1.RowDefinitions[1].Height = new GridLength(50, GridUnitType.Star);
            }
        }

        void newChart_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void bPrev_Click(object sender, RoutedEventArgs e)
        {
            bNext.IsEnabled = false;
            bPrev.IsEnabled = false;
            try
            {
                if (isZoom)
                    return;

                m_currentPage -= 1;
                //int controls = grid1.Children.Count - 1;
                for (int controls = 1; controls <= 4; controls++)
                {
                    try
                    {
                        Chart customChart = (Chart)grid1.Children[controls];
                        customChart.Title = "";

                        if (customChart.Series.Count > 0)
                            for (int ser = 0; ser <= customChart.Series.Count(); ser++)
                                customChart.Series.RemoveAt(0);

                        if (customChart.Axes.Count > 0)
                            for (int ser = 0; ser <= customChart.Axes.Count(); ser++)
                                customChart.Axes.RemoveAt(0);


                    }
                    catch
                    {
                    }
                }

                ThreadPool.QueueUserWorkItem(delegate
                {
                    int s_currentChart = 1;
                    for (int i = (4 * m_currentPage); i <= (4 * m_currentPage) + 3; i++)
                    {
                        MChart chart = null;
                        Chart customChart = null;

                        //get the chart from grid


                        if (i <= m_loaded.Count - 1)
                        {
                            bool passed = false;
                            chart = m_loaded[i];
                            Dispatcher.BeginInvoke(delegate
                            {
                                customChart = (Chart)grid1.Children[s_currentChart];
                                customChart.Visibility = System.Windows.Visibility.Visible;
                                customChart.Tag = chart.Get_ID();
                                customChart.Title = chart.GetName();
                                passed = true;
                            });

                            while (!passed)
                                Thread.Sleep(1);

                            passed = false;
                            //Chart customChart = (Chart)tableLayoutPanel1.Controls[s_currentChart];


                            AddSeriesToChart(customChart, chart);
                        }
                        else
                        {
                            bool passed = false;
                            Dispatcher.BeginInvoke(delegate
                            {
                                customChart = (Chart)grid1.Children[s_currentChart];
                                customChart.Visibility = System.Windows.Visibility.Collapsed;
                                passed = true;
                            });

                            while (!passed)
                                Thread.Sleep(1);
                        }
                        s_currentChart++;
                        //Chart tbChart = (Chart)tableLayoutPanel1.Controls[i];
                        //tableLayoutPanel1.Controls.Remove(tbChart);
                    }
                });


                if (m_currentPage > 0)
                {
                    bPrev.IsEnabled = true;
                }
                else
                {
                    bPrev.IsEnabled = false;
                }
                bNext.IsEnabled = true;

            }
            catch
            {
            }
        }

        private void bNext_Click(object sender, RoutedEventArgs e)
        {
            bNext.IsEnabled = false;
            bPrev.IsEnabled = false;

            try
            {
                if (isZoom)
                    return;

                m_currentPage += 1;
                //int controls = grid1.Children.Count - 1;
                for (int controls = 1; controls <= 4; controls++)
                {
                    try
                    {
                        Chart customChart = (Chart)grid1.Children[controls];
                        customChart.Title = "";

                        if (customChart.Series.Count > 0)
                            for (int ser = 0; ser <= customChart.Series.Count(); ser++)
                                customChart.Series.RemoveAt(0);

                        if (customChart.Axes.Count > 0)
                            for (int ser = 0; ser <= customChart.Axes.Count(); ser++)
                                customChart.Axes.RemoveAt(0);


                    }
                    catch
                    {
                    }
                }

                ThreadPool.QueueUserWorkItem(delegate
                {
                    int s_currentChart = 1;
                    for (int i = (4 * m_currentPage); i <= (4 * m_currentPage) + 3; i++)
                    {
                        MChart chart = null;
                        Chart customChart = null;

                        //get the chart from grid


                        if (i <= m_loaded.Count - 1)
                        {
                            bool passed = false;
                            chart = m_loaded[i];
                            Dispatcher.BeginInvoke(delegate
                            {
                                customChart = (Chart)grid1.Children[s_currentChart];
                                customChart.Visibility = System.Windows.Visibility.Visible;
                                customChart.Tag = chart.Get_ID();
                                customChart.Title = chart.GetName();
                                passed = true;
                            });

                            while (!passed)
                                Thread.Sleep(1);

                            passed = false;
                            //Chart customChart = (Chart)tableLayoutPanel1.Controls[s_currentChart];


                            AddSeriesToChart(customChart, chart);
                        }
                        else
                        {
                            bool passed = false;
                            Dispatcher.BeginInvoke(delegate
                            {
                                customChart = (Chart)grid1.Children[s_currentChart];
                                customChart.Visibility = System.Windows.Visibility.Collapsed;
                                passed = true;
                            });

                            while (!passed)
                                Thread.Sleep(1);

                        }
                        s_currentChart++;
                        //Chart tbChart = (Chart)tableLayoutPanel1.Controls[i];
                        //tableLayoutPanel1.Controls.Remove(tbChart);
                    }
                });


                if (m_loaded.Count / 4.0 > (m_currentPage + 1))
                {
                    bNext.IsEnabled = true;
                    bPrev.IsEnabled = true;
                }
                else
                {
                    bNext.IsEnabled = false;
                    bPrev.IsEnabled = true;
                }

            }
            catch
            {
            }
        }
    }
}
